var express = require('express');
var router = express.Router();
var utils = require('../../functions/utils');

router.post('/', function(req,res)
{
	var sessionKey = req.session.key;

	if(utils.isValidString(sessionKey))
	{
		var async = require('async');
		async.waterfall([
			function(cb)
			{
				utils.checkManagerSession(sessionKey , cb);
			}
			,function(result , cb) 
			{
				// 실패 - 로그인 페이지 
				if(result == 0)
				{
					utils.notifyManagerSessionExpired(req , res);
				}
				// 성공 - 실제 작업코드.
				else
				{	
				/////////////////////////////////////////////////////////////////////////////////////////////	
				/*
					Input parameters 

					date

				*/

					var date = req.body.date;
					var osId = req.body.osId;
					if(!utils.isValidString(osId))
						osId=1;

					var zoomLevel = req.body.zoomLevel;
					if(!utils.isValidString(zoomLevel))
						zoomLevel=2;

					var centerLat = req.body.centerLat;
					if(!utils.isValidString(centerLat))
						centerLat=30;

					var centerLon = req.body.centerLon;
					if(!utils.isValidString(centerLon))
						centerLon=150;



					var db = global.replica_db;

					var fs = require('fs');
					fs.readFile('./template/articleLocations' , function(error,data)
					{
						if(error)
						{
							throw error;
						}
						var html = String(data);


						db.connection.getConnection(function(err,connection)
						{
							if(err)
							{
								throw err;
							}

							
							var input_param = [date];

							var sql = 'call manage_getArticleLocations(?)';

							var query = connection.query(sql, input_param , function (err, rows) 
							{
								connection.release();
								if(err)
								{
									throw err;
								}

								html = html.split("%DATE%").join(date); 
								html = html.split("%OS_ID%").join(osId); 
								html = html.split("%ZOOM_LEVEL%").join(zoomLevel); 
								html = html.split("%CENTER_LAT%").join(centerLat); 
								html = html.split("%CENTER_LON%").join(centerLon); 


								// 등록된 위치가 없다.
								if(rows[0].length == 0 && rows[1].length == 0)
								{
									html = html.split("%CLOSE_WINDOW%").join('true'); 

									html = html.split("%ANDROID_LOCATIONS%").join(''); 
									html = html.split("%IOS_LOCATIONS%").join(''); 

								}
								else
								{
									html = html.split("%CLOSE_WINDOW%").join('false'); 

									var andLocationString = '';
									var andIdString = '';
									var andEncIdString = '';

									var iOSLocationString = '';
									var iOSIdString = '';
									var iOSEncIdString = '';


									for(var i = 0 ; i < rows[0].length ; i ++)
									{
										if(-90 <= rows[0][i].lat && rows[0][i].lat <= 90
											&& -180 <= rows[0][i].lat && rows[0][i].lat <= 180)
										{
											andLocationString += '{lat: ' + rows[0][i].lat 
																+ ', lng: ' + rows[0][i].lon 
																+ ', articleId: ' + rows[0][i].articleId
																+ ', encId: \'' + rows[0][i].encId + '\'},';
										}
										else
										{
											console.log('and err : ' + JSON.stringify(rows[0][i]));
										}
									}



									for(var i = 0 ; i < rows[1].length ; i ++)
									{
										if(-90 <= rows[1][i].lat && rows[1][i].lat <= 90
											&& -180 <= rows[1][i].lat && rows[1][i].lat <= 180)
										{
											iOSLocationString += '{lat: ' + rows[1][i].lat 
																+ ', lng: ' + rows[1][i].lon 
																+ ', articleId: ' + rows[1][i].articleId
																+ ', encId: \'' + rows[1][i].encId + '\'},';
										}
										else
										{
											console.log('iOS err : ' + JSON.stringify(rows[1][i]));
										}
									}


									console.log('and count : ' + rows[0].length + ', iOS count : ' + rows[1].length);
									

									html = html.split("%ANDROID_LOCATIONS%").join(andLocationString); 

									html = html.split("%IOS_LOCATIONS%").join(iOSLocationString); 

								}

								res.writeHead(200 , {'Content-Type' : 'text/html; charset=utf-8'});
								res.end(html);

							}); // query

						}); // getConnection

					}); // readfile
			//////////////////////////////////////////////////////////////////////////////////////////

				} // result==1 
			}
		]); //waterfall
	}
	// 암것도 없으면 loginPage
	else
	{
		utils.gotoManagerLoginPage(req , res);
	}
});

module.exports = router;